﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using ProgNetComponentsDx.Options;

namespace BuildHelper.Kontakt
{
    public partial class KontaktFormNew : XtraForm
    {
        public KontaktFormNew()
        {
            InitializeComponent();
        }
        private Client client;

        public KontaktFormNew(Client client):this()
        {
            this.client = client;
            this.btnList.Visible = KontaktTools.IsServer;
        }

        public Dictionary<string, XtraTabPage> pages = new Dictionary<string, XtraTabPage>();

        private void teText_KeyDown(object sender, KeyEventArgs e)
        {
            if (ceSendOnEnter.Checked)
            {
                if (e.KeyCode == Keys.Enter && !e.Shift)
                {
                    Send();
                    e.Handled = true;
                    this.BeginInvoke(new Action(Clear));
                }
            }
        }
        private void Clear()
        {
            memoText.Text = "";
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            Send();
        }

        protected virtual void Send()
        {
            if (memoText.Text.IsNotNullOrEmpty())
            {
                try
                {
                    XtraTabPage p = xtraTabControl1.SelectedTabPage;
                    if (p != null)
                    {
                        if (client != null)
                        {
                            string m = DefaultMessages.MSG_START +
                            DefaultMessages.MSG_RECEIVER_ID + p.Tag.AsString() + DefaultMessages.MSG_RECEIVER_ID +
                            memoText.Text +
                            DefaultMessages.MSG_END;
                            client.Send(m);

                            AppendMyText(memoText.Text);
                            memoText.Text = "";
                        }
                    }
                }
                catch
                {
                    this.ShowDxErrorDialog("Problem z połączeniem!");
                }
            }
        }
       
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (!Program.IsExit)
            {
                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Kontakty.CzyscWiadomosci))
                {
                    foreach (KeyValuePair<string, XtraTabPage> kvp in pages)
                    {
                        kvp.Value.Controls[0].Text = "";
                    }
                }
                e.Cancel = true;
                Hide();
            }
        }

        public void AppendText(string id, string nick, string text)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, string, string>(AppendText), id, nick, text);
                return;
            }
            
            if (!this.Visible)
                this.Reshow();
            string prefix = nick;
            if (nick.Contains("*"))
            {
                nick = nick.Replace("*", "");
                prefix = "*******  ";
            }

            xtraTabControl1.SelectedTabPage = EnsurePage(nick, id);
            MemoEdit m = xtraTabControl1.SelectedTabPage.Controls[0] as MemoEdit;
            bool adddate = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Kontakty.PokazujCzas);

            m.AppendText(prefix + (adddate ? "(" + DateTime.Now.ToString() + "): " : "") + "\r\n");
            m.AppendText(text.Replace("\f","\n").ReplaceSingleEOL() + "\r\n");
        }
        public void AppendMyText(string text)
        {
            if (client != null)
            {
                if (!this.Visible)
                    this.Reshow();
                if (xtraTabControl1.SelectedTabPage != null)
                {
                    MemoEdit m = xtraTabControl1.SelectedTabPage.Controls[0] as MemoEdit;
                    bool adddate = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Kontakty.PokazujCzas);

                    m.AppendText(client.Login + (adddate ? " (" + DateTime.Now.ToString() + "): " : "") + "\r\n");
                    m.AppendText(text + "\r\n");
                }
            }
        }
        public XtraTabPage EnsurePage(string nick, string id)
        {
            XtraTabPage p;
            if (pages.ContainsKey(nick))
            {
                p = pages[nick];
            }
            else
            {
                p = new XtraTabPage();
                p.Tag = id;
                MemoEdit memo = new MemoEdit();
                memo.Properties.ReadOnly = true;
                memo.Dock = DockStyle.Fill;
                p.Controls.Add(memo);
                if (nick.IsNotNull())
                {
                    p.Text = nick;
                }
                else
                {
                    p.Text = "Wszyscy";
                }
                pages.Add(nick, p);
            }
            if (!xtraTabControl1.TabPages.Contains(p))
                xtraTabControl1.TabPages.Add(p);
            return p;
        }
        private void xtraTabControl1_CloseButtonClick(object sender, EventArgs e)
        {
            XtraTabPage p = xtraTabControl1.SelectedTabPage;
            if (p != null)
            {
                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Kontakty.CzyscWiadomosci))
                {
                    p.Controls[0].Text = "";
                }
                xtraTabControl1.TabPages.Remove(p);
                pages.Remove(p.Tag.AsString());
                if (xtraTabControl1.TabPages.Count == 0)
                    Close();
            }
        }

        internal void Reshow()
        {
            if (client == null)
                return;
            Text = "Kontakt [" + client.Login + "]";
            memoText.Text = "";
            xtraTabControl1.TabPages.Clear();
            if (!this.Visible)
                Show(FormMain.Instance);
            User32.SetForegroundWindow(this.Handle);
        }

        internal void ConnectWithUser(string nick, string id)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, string>(ConnectWithUser), nick, id);
                return;
            }
            try
            {
                if (!Visible)
                    Visible = true;

                Reshow();
                EnsurePage(nick, id);

                User32.SetForegroundWindow(this.Handle);
            }
            catch { }
        }

        private void btnList_Click(object sender, EventArgs e)
        {
            if (KontaktTools.IsServer)
            {
                KontaktUsersFormNew f = new KontaktUsersFormNew(Server.Instance.OwnerClinet);
                f.Show();

            }
        }
    }
}
